package com.cdu.eduPanda.project.utils;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.time.Duration;

import static com.cdu.eduPanda.project.common.constant.RedisCacheConstant.USER_REGISTER_KEY;

@Component
@RequiredArgsConstructor
public class MailMsgUtil {

    private final JavaMailSenderImpl mailSender;
    private final RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}")
    private String sendEmail;

    public boolean mail(String email) throws MessagingException {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //生成随机验证码
        String code = CodeGeneratorUtil.generateCode(6);
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //设置一个html邮件信息
        helper.setText("<p>尊敬的用户，您好！您正在注册edu-panda账号，请在邮件验证码输入框中输入下方验证码(有效期1分钟):</p><br/>" + code
                , true);
        //设置邮件主题名
        helper.setSubject("edu-panda注册验证码");
        //发给谁-》邮箱地址
        helper.setTo(email);
        //谁发的-》发送人邮箱
        helper.setFrom(sendEmail);
        //将邮箱验证码以邮件地址为key存入redis,1分钟过期
        redisTemplate.opsForValue().set(USER_REGISTER_KEY + email, code, Duration.ofMinutes(1));
        mailSender.send(mimeMessage);
        return true;
    }
}
